﻿using System;
using System.Web;
using System.Web.Mvc;
using Peak.ApplicationServices;
using Peak.ApplicationServices.Services;
using Peak.Core;
using MvcContrib;
using Peak.Core.DataInterfaces;
using Peak.Web.Controllers.Services;
using SharpArch.Core.PersistenceSupport;
using SharpArch.Web.NHibernate;
using System.Linq;
using Peak.Web.Controllers.Models;
using System.Threading;

namespace Peak.Web.Controllers
{
  public class ProjectsController : BaseController
  {
    private readonly IProjectService _projectService;
    
    public ProjectsController(ISessionService sessionService, IProjectService projectService)
      : base(sessionService)
    {
      _projectService = projectService;    
    }

    public ActionResult CheckDefault()
    {
      if (_sessionService.User.Profile.DefaultProject != null)
      {
        return SelectProject(_sessionService.User.Profile.DefaultProject.Id);
      }
      if(_sessionService.IsProjectSelected)
      {
        return SelectProject(_sessionService.Project.Id);
      }
      return this.RedirectToAction(f => f.Index());
    }

    public ActionResult Index()
    {
      return View(_projectService.GetAllByAssignedTo(Thread.CurrentPrincipal.Identity.Name).Select(f => new ProjectModel(f, f == _sessionService.User.Profile.DefaultProject)).ToList());
    } 
    
    public ActionResult SelectProject(int projectId)
    {
      if (Response.Cookies[SessionService.CurrentProjectId] != null)
      {
        try
        {
          _projectService.Get(projectId);
          Response.Cookies[SessionService.CurrentProjectId].Value = projectId.ToString();
        }
        catch(EntityNotFoundException)
        {
          return this.RedirectToAction(f => Index());          
        }        
      }
      else
      {
        HttpCookie hc = new HttpCookie(SessionService.CurrentProjectId, projectId.ToString());
        hc.Expires = DateTime.Now.AddYears(1);
        Response.Cookies.Add(hc);
      }
      return this.RedirectToAction<DashboardController>(f => f.Index(null));
    }
       
    [Transaction]
    public ActionResult Remove(int projectId)
    {
      Project project = _projectService.Get(projectId);
      if (project == null)
        return this.RedirectToAction<ErrorsController>(f => f.InvalidUserOperation());

      if (_sessionService.User.DefaultProject != null && _sessionService.User.DefaultProject.Id == projectId)
      {
        _sessionService.User.DefaultProject = null;        
      }

      _projectService.Delete(project);
      if (_sessionService.Project != null && _sessionService.Project.Id == projectId)
      {
        Response.Cookies.Remove(SessionService.CurrentProjectId);
      }
      
      return this.RedirectToAction(f => f.Index());
    }
  }
}
